const express = require('express');
const helmet = require('helmet');
const app = express();
// Use helmet middleware
app.use(helmet());Developing secure software is as much a philosophy as a skill
As developers we’re often asked to “Make it work!”
Later we work on “Make it safe!”
This course aims to get you thinking earlier about security in the design and development process
notes: DevOps and DevSecOps are big buzzwords. In general the idea is find bugs or vulnerabilities earlier in the design and development process and provide open communication about the issues, risks, and corrections of those issues to everyone in the DevOps cycle.
Confidentiality
Determines the secrecy of the information asset.
Integrity
Provides the assurance that the data is accurate and reliable.
Availability
The ability of the users to access an information asset.
Protection of disclosure to unauthorized parties
Any information leak can be catastrophic
Includes protection from disclosure of:
stored data
restricted data
communication traffic
communication content
Protection of information from alteration, creation, or destruction by unauthorized parties
Any alteration or threat of alteration may be catastrophic
Includes protection from:
data file modification
program file modification
replication, altering, deleting, creating new or false data
Assurance that systems and system resources will be accessible when needed
Attacks often called DoS (Denial of Service)
A temporary restriction of access
Permanent restriction is failure of integrity
Includes protection from:
Excessive requests impeding ability to serve clients
System rendered inoperable by removal of files/components/applications
Overloading parts of the system leading to crashes
A three-process framework
Used to manage user access
Enforce user policies and privileges
Measure the consumption of network resources
The unproven assertion of who you are
For example:
A username
An ID card
A bank card
A user providing information about who they are and proving it
Users or systems present login credentials that affirm they are who they claim to be
Authorization follows authentication
A user can be granted privileges to access certain areas of a network, application, or system
Areas and sets of permissions granted a user are often stored in a database along with the user’s identity
The user’s privileges can be changed by an administrator or developer with access to the database
Tracking user activity while users interact with the system
Often logging what data accessed or services used
May be used to:
Analyze user trends
Audit user activity
Provide early warning of misuse
AKA principle of minimal privilege (PoMP) or the principle of least authority (PoLA)
Every entity (such as a process, a user, or a program) must be able to access only the information and resources that are necessary for its legitimate purpose
Ensures one individual cannot complete a critical task by themselves
Reduces the possibility for fraud, sabotage, theft or general abuse
Requires collusion of two or more parties to circumvent
Provides proof of the origin, authenticity, and integrity of data.
Ensures that no party can deny sending or receiving a message
Ensures no party can contest the authenticity of their signature on a document
A cybersecurity approach that involves layering multiple defensive mechanisms to protect valuable data and information
If one mechanism fails, there are other layers of defense in place to prevent or mitigate an attack
Addresses different attack vectors and provides a more robust and resilient security posture
Follow secure coding practices
Stay updated on the latest security vulnerabilities
Learn best practices in web application security
Asset
The object which requires protection
Attack path
The mechanism taken by an attacker to access an asset
Attack surface
The sum of all the possible attack paths
Defects/weaknesses
Errors that could result in unexpected or undesired behavior
Vulnerability
A defect that can be exploited to compromise a system
Threats
A harm that might be caused by an attacker
Exploit
When an attacker uses a vulnerability to cause harm
Hackers
Users
Insiders
Buffer overflow
Command injection
SQL injection
Cross site scripting
| Objectives |
|---|
Key objectives of this chapter
|
An evolving set of cybersecurity paradigms
A security framework that requires all users to be authenticated, authorized, and continuously validated before being granted access to resources
Assumes no implicit trust granted to assets or user accounts based solely on their physical or network location
The main mantra: Never Trust! Always Verify!
Never trust, always verify
Principle of least privilege
Move security away from the perimeter to the application itself
Continuous monitoring and analytics
Embrace adaptability and flexibility
Systems operating under a Zero Trust framework do not initially trust access or transactions from anyone, including internal users
Always authenticate and authorize based on all available data points, including
User identity
Location
Service or workload
Data classification
Any anomalies
Minimize blast radius and segment access to modules or components of your application
Verify end-to-end encryption
Use analytics to get visibility, drive threat detection, and improve defenses
Limit user access with
Just-in-time
Just-enough access
Risk-based adaptive polices
Data protection to help secure both data and productivity
This applies to insiders as well!
Verify and secure each identity with strong authentication across your entire digital estate.
Gain visibility into devices accessing the network.
Ensure compliance and health status before granting access.
Ensure that devices and users aren’t trusted just because they’re on an internal network.
Encrypt all internal communications, limit access by policy, and employ micro-segmentation and real-time threat detection.
Discover shadow IT, ensure appropriate in-app permissions, gate access based on real-time analytics, and monitor and control user actions.
Use telemetry to detect attacks and anomalies, automatically block and flag risky behavior, and employ least-privilege access principles.
Move from perimeter-based data protection to data-driven protection.
Use intelligence to classify and label data.
Encrypt and restrict access based on organizational policies.
Incorporate Zero Trust principles throughout the development cycle
Not a replacement for security fundamentals, developers should still follow best practices
Manage and secure data where no actual perimeter exists such as cloud services
Developers should verify the security of open source and third-party components used in their projects and apply updates and fixes as necessary
| Objectives |
|---|
Key objectives of this chapter
|
The Open Web Application Security Project formed in 2003, a foundation that focuses on software security. It supports the security industry with the OWASP Top 10.
| Vulnerability | Description |
|---|---|
1. Broken access control |
failures can jeopardize information disclosures and data integrity |
2. Cryptographic failures |
concerns data exposure and compromises confidentiality |
3. Injection |
involves hostile data use, attacks, and unsafe queries |
4. Insecure design |
covers weaknesses and flaws in control designs |
5. Security misconfiguration |
involves features that are incorrectly enabled or have other configuration |
| Vulnerability | Description |
|---|---|
6. Vulnerable and outdated components |
involve version control and other compatibility issues |
7. Identification and authentication failures |
covers password issues, automated attacks like credential stuffing, and session |
8. Software and data integrity failures |
involve integrity violations, which are often from untrusted sources |
9. Security and logging and monitoring failures |
involve detecting and responding to breaches |
10. Server-side request forgery |
results in URL validation failures |
Activities that should take place:
Before development begins
During definition and design
During development
During deployment and
During maintenance and operations
Injection attacks occur when untrusted data is sent to an interpreter
Can lead to data loss, corruption, or unauthorized data disclosure
Includes SQL injection where user input constructs a SQL query without proper validation or escaping
Incorrect implementation of session management and authentication functions
May compromise passwords, keys, or session tokens
Weak password enforcement can lead to unauthorized access
Occurs when sensitive data is inadequately protected
Transmitting sensitive data over HTTP instead of HTTPS can lead to exposure
XXE attacks happen with XML input containing external entity references
Can result in disclosure of internal files, denial of service, or remote code execution
Flaws in enforcing restrictions on authenticated users
Allows attackers to access unauthorized functionality or data
Using default or incomplete configurations can lead to unauthorized access
Misconfigurations can expose private information, such as directory listing vulnerabilities
Flaws in adding untrusted data to web pages
Attackers can execute malicious scripts, hijack sessions, deface websites, or redirect users
Insecure deserialization allows remote code execution
Can lead to replay attacks, injection attacks, and privilege escalation
Inadequate logging and monitoring give attackers opportunities to persist and pivot
Proper logging and monitoring are crucial for timely detection and response
| Objectives |
|---|
Key objectives of this chapter
|
Confusion (substitution )
Diffusion (transposition)
Secrecy only in the key
Encryption - the method of transforming data (plaintext) into an unreadable format
Plaintext - the format (usually readable) of data before being encrypted
Ciphertext - the "scrambled" format of data after being encrypted
Decryption - the method of turning cipher text back into plaintext
Encryption algorithm a set or rules or procedures that dictates how to encrypt and decrypt data, also called an encryption cipher
Key - (cryptovariable) a value used in the encryption process to encrypt and decrypt
AES (Advanced Encryption Standard): AES is widely used and considered secure. It supports key sizes of 128, 192, and 256 bits.
ChaCha20: ChaCha20 is a stream cipher that is gaining popularity due to its speed and security.
RSA (Rivest-Shamir-Adleman)
Elliptic Curve Cryptography (ECC)
Diffie-Hellman Key Exchange (DH
DSA (Digital Signature Algorithm)
ECDSA (Elliptic Curve Digital Signature Algorithm)
ElGamal
Hashing is a one-way operation
Converts a large amount of data into a fixed length value (hash digest)
Family of cryptographic functions published by NIST
SHA-3 (formerly Keccak) is the most recent
Used to establish integrity
Combined with encryption algorithms can be used as part of a digital signature
A set of hardware, software, people, policies, and procedures needed to create, manage, distribute, use, store, and revoke digital certificates
Enables C and I of the CIA triad
Enables non-repudiation
Each person or server can have a digital certificate
Has information about a person, including a person’s public key
Typically, not attached to a person but to a server or system
Certificates are signed by a Certificate Authority
The Certificate Authority vouches for each organization’s certificate
Some certificates can be self-signed
Typically, organizations purchase wildcard certificates from authorities such as Let’s Encrypt, Verisign, or Thawte
A standard format for public key certificates
Applications:
SSL/TLS
Signed and encrypted email
Code signing
Document signing
Client authentication
Government-issued electronic IDs
A public key
Part of a key pair that also includes a private key
Private key is kept secure
Only the public key is included in the certificate
A digital signature
Information about both the identity associated with the certificate and its issuing certificate authority (CA)
An encoded hash (fixed-length digest) of a document that has been encrypted with a private key
Fields specifying the subject, issuing CA, validity and other and other required information
Encrypt data in transit
Its successor is TLS (Transport Layer Security)
Both are protocols for establishing authenticated and encrypted links between networked computers
Encrypts plaintext, like passwords, and credit card numbers
Only the user and the website can decrypt
Ensures the data remain unchanged
Authenticates websites
Modern browsers show warnings when the connection is NOT entirely secure
Identify an individual, server, or organization
A digital document that binds the identity of a website to a cryptographic key pair
The key pair consists of a public key and a private key
The public key, included in the certificate, allows a web browser to initiate an encrypted communication session with a web server via the TLS and HTTPS protocols
The private key is kept secure on the server, and is used to digitally sign web pages and other documents (such as images and JavaScript files)
HTTPS (Hypertext Transfer Protocol Secure) is a secure version of the HTTP protocol
Uses the SSL/TLS protocol for encryption and authentication
HTTPS is specified by RFC 2818 (May 2000) and uses port 443 by default instead of HTTP’s port 80
Encryption
Authentication
Integrity
Validation
Domain validation (DV)
Organization/Individual validation (OV/IV)
Extended validation (EV)
Adds encryption to the HTTP protocol by wrapping HTTP inside the SSL/TLS protocol
Which is why SSL is called a tunneling protocol)
All messages are encrypted in both directions between two networked computers including:
Request URL (which web page was requested by the client)
Website content
Query parameters
Headers
Cookies
Uses digital documents known as X.509 certificates
Binds cryptographic key pairs to the identities of entities such as websites, individuals, and companies
Each key pair includes
a private key, which is kept secure
a public key, which can be widely distributed
Anyone with the public key can use it to:
send data that only the private key possessor can decrypt
confirm that data has been digitally signed by the corresponding private key
| Property | Code-signing | SSL/TLS |
|---|---|---|
Purpose |
Digitally sign software code, ensuring its integrity and authenticity |
Used to establish secure encrypted connections between a client (such as a web browser) and a server |
Protection |
Protect end-users by guaranteeing the integrity of the code they download |
Protect end-users by securing communication between their browsers and websites |
Outcome |
Verifies that the code has not been tampered with and comes from a trusted source |
Ensures that the communication between the client and server is encrypted and secure, protecting sensitive data during transmission |
| Objectives |
|---|
Key objectives of this chapter
|
The process of verifying the identity of a given user or client
Making sure that they really are who they claim to be
Most websites are exposed to anyone who is connected to the internet by design
Robust authentication mechanisms are vital to effective web security
something you know
something you have
something you are or do
Authentication
Verifying that a user really is who they claim to be
Authorization
Verifying whether a user is allowed to do something
Allows users to log in to one application and be automatically signed in to other applications, regardless of platform or domain
Provides a seamless user experience
Eliminates the need to remember multiple credentials for different applications.
Example: Google’s SSO - logging in to Gmail automatically authenticates the user to YouTube, AdSense, Google Analytics, and more
Users log in to one domain, which serves as the authentication domain.
Authentication Domain: The domain responsible for verifying user credentials.
Redirection: When accessing a domain requiring authentication, users are redirected to the authentication domain.
Already Logged-In Users: If already logged in at the authentication domain, users are immediately redirected back to the original domain without signing in again.
Logging out of one application automatically logs the user out of all associated applications.
Example: Logging out of Gmail also logs the user out of other Google apps.
Benefit of SLO: Ensures a secure logout process across all applications.
Advantages of SSO:
Enhanced User Experience: Users only need to log in once for access to all applications.
Simplified Credential Management: No need to remember separate login details for each app.
Increased Security: Centralized authentication and logout process.
Implementing SSO for MERN Stack:
Choose a reliable SSO solution.
Integrate the SSO solution into your MERN application.
Configure authentication and redirection domains.
Test the SSO functionality thoroughly.
Select an SSO provider that fits your project requirements
Popular options include Auth0 and Okta
Follow the provider’s documentation to create an account, set up an application, and configure the necessary settings
Build user authentication functionality in your MERN stack application using a popular library like Passport.js or JSON Web Tokens (JWT)
Establish user roles and permissions to control access to different parts of your application
Utilize the SDKs or libraries provided by your chosen SSO provider to integrate SSO functionality into your application
Implement the necessary code and configurations to enable SSO login and logout flows
Thoroughly test your SSO implementation to ensure seamless authentication and authorization across your application
Implement appropriate security measures like using HTTPS, securely storing and handling user data, and applying necessary security best practices.
An authorization framework that enables applications — such as Facebook, GitHub, and DigitalOcean — to obtain limited access to user accounts on an HTTP service
Works by delegating user authentication to the service that hosts a user account and authorizing third-party applications to access that user account
OAuth 2 provides authorization flows for web and desktop applications, as well as mobile devices
Resource Owner: the user who authorizes an application to access their account. The application’s access to the user’s account is limited to the scope of the authorization granted (e.g. read or write access)
Client: the application that wants to access the user’s account. Before it may do so, it must be authorized by the user, and the authorization must be validated by the API.
Resource Server: The resource server hosts the protected user accounts.
Authorization Server: The authorization server verifies the identity of the user then issues access tokens to the application.
An interoperable authentication protocol based on the OAuth 2.0 framework of specifications (IETF RFC 6749 and 6750)
Simplifies the way to verify the identity of users based on the authentication performed by an Authorization Server
Obtains user profile information in an interoperable and REST-like manner
Enables application and website developers to launch sign-in flows and receive verifiable assertions about users across Web-based, mobile, and JavaScript clients
Is extensible to support a range of optional features such as encryption of identity data, discovery of OpenID Providers, and session logout
| Objectives |
|---|
Key objectives of this chapter
|
A security discipline that focuses on controlling and managing user access to resources within an organization
For MERN developers, plays a crucial role in ensuring that the right individuals or job roles have the appropriate access to the tools and functionalities they need to perform their tasks
Confirming and storing information about a user’s identity, such as their job title and permissions
Ensures that the user is who they claim to be and authenticates their identity
An identity management database holds information about the user’s identity and attributes
Uses the information from identity management to determine what resources and functionalities a user is allowed to access
Controls and monitors network access, ensuring that users have the necessary permissions to perform their tasks
Access management systems manage a range of identities, including people, software, and hardware devices
The process of determining what actions a user can perform within an application based on their identity, roles, and permissions
Granting or denying access to specific resources or functionalities based on the user’s authorization level
Privileged accounts: accounts with elevated permissions that have access to critical systems, sensitive data, and administrative functions
For these accounts, PAM
Manages
Secures
Controls
Monitors
Designed for managing access for
privileged users
system administrators
IT staff
other users with elevated privileges
focuses on securing and controlling access to privileged accounts
enforces the principle of least privilege
implements additional security measures:
session monitoring
password management
multi-factor authentication for privileged users
IAM manages user identities, authentication, and authorization for all users within an organization
IAM controls access to resources such as applications, databases, and network resources based on user roles, permissions, and policies
PAM is a subset of IAM that specifically focuses on managing access to privileged accounts and critical resources
PAM systems enforce stricter controls and monitoring for privileged accounts to prevent unauthorized access and mitigate the risk of insider threats
PAM helps organizations implement the principle of least privilege, granting privileged access only when necessary and for a limited time
IAM and PAM are both important for maintaining security, compliance, and effective access management strategies within an organization
Okta: A popular IAM platform that provides authentication, authorization, and user management capabilities
Auth0: A flexible IAM solution that offers features like single sign-on (SSO), social login, and user management
Keycloak: An open-source IAM solution that provides features like SSO, user federation, and identity brokering
AWS IAM: Amazon Web Services Identity and Access Management (IAM) service for managing access to AWS resources
CyberArk: A leading PAM solution that offers features like password management, session monitoring, and privileged session recording.
BeyondTrust Privilege Management: A PAM solution that focuses on managing and securing privileged access to critical resources.
Thycotic Secret Server: A PAM solution that provides secure storage and management of privileged account credentials.
HashiCorp Vault: A popular open-source tool for managing secrets and protecting privileged access
| Objectives |
|---|
Key objectives of this chapter
|
Apply a strong management policy to passwords, tokens, keys, and other privileged information
Separate secrets from source code
Use a secure configuration approach
Employ encryption for secrets
Use secrets management tools
Follow other security best practices
Never hardcode sensitive information (such as API keys, database credentials, or passwords) directly into your source code
Use environment variables or a secrets management solution to store and access these secrets securely
Consider using a tool like dotenv to load environment variables from a
.env file during development
Implement a configuration module or file that holds your secrets and configuration settings
Ensure that this configuration file is properly protected and only accessible to authorized users
Avoid committing the configuration file to your version control system (e.g., Git) to prevent accidental exposure
Use techniques like .gitignore to exclude sensitive files
Encrypt sensitive data at rest, such as credentials stored in databases or files
Consider using encryption libraries or frameworks provided by your chosen MERN stack components (e.g., bcrypt for password hashing in Node.js, or built-in encryption features of MongoDB)
Encrypt sensitive data in transit using secure communication protocols (e.g., HTTPS) and encryption libraries (e.g., SSL/TLS)
Take advantage of secrets management tools specifically designed for developers, such as HashiCorp Vault or AWS Secrets Manager
These tools offer secure storage, retrieval, and rotation of secrets, as well as access control and audit logs
Integrate these tools into your MERN stack application by utilizing appropriate client libraries or SDKs
Regularly update and patch dependencies and libraries used in your MERN stack application to mitigate security vulnerabilities
Implement proper authentication and authorization mechanisms to ensure only authorized users can access sensitive data and perform privileged actions
Implement secure coding practices, such as input validation, output encoding, and protection against common web application vulnerabilities like cross-site scripting (XSS) and SQL injection
| Objectives |
|---|
Key objectives of this chapter
|
Use JWT for user authentication and authorization
Implement JWT in the backend
Store JWT securely on the client-side
Refresh and revoke JWTs
Cryptography and hashing algorithms should not be implemented from scratch
Best to use battle-tested libraries like CryptoJS.
Server should handle the signing and verification of JWTs, it is the only place that can securely handle secrets and properly verify tokens
If any part of the payload is altered, the signature will change, which helps ensure the integrity of the JWT and prevents tampering
JWTs can be transmitted in the URL bar but should be handled carefully to ensure URL safety and prevent potential issues with certain characters
Use a library like JSON Web Token from npm rather than writing the signing code manually
Install using npm
Import into the project using import * as jwt from 'jsonwebtoken'
Use a strong, long, and complex secret key
Token payload includes claims such as “sub” for subjects and “iss” for issuer
Use the jwt.sign() method
Pass payload, secret key, and any additional options as arguments to this method
Set an expiration time for the token using the “exp” claim
After signing the token, optionally log to the console or process further
Do use long, strong, and unguessable secrets (e.g., 256-bit) for signing tokens
Do keep the token payload small to reduce the token size
Do ensure that HTTPS is used to secure the connection
Don’t store tokens in local storage
Don’t store secret keys used for signing tokens in the browser
Don’t decode tokens on the client side, especially access tokens
Don’t put anything in the body of a JWT that the user/client should not be able to see
| Objectives |
|---|
Key objectives of this chapter
|
Use enterprise tools and patterns
Protect sensitive data
Think Zero Trust!
Provide Resiliency (backup/restore)
Server-side validation
Isolate security functions
Application partitioning
Re-authorize high-value transactions
Provide logging and monitoring
Implement user authentication and authorization
Protect against cross-site scripting (XSS) attacks
Prevent cross-site request forgery (CSRF) attacks
Securely handle and store sensitive data
Regularly update and patch dependencies
Understand and vet open-source resources and third-party tools
Regularly update dependencies
Verify package authenticity
Implement secure coding practices
Continuously monitor for vulnerabilities
Provides a set of guidelines, best practices, and standards for managing and improving cybersecurity risk
Helps organizations assess and enhance their cybersecurity posture by focusing on five core functions
Identify
Protect
Detect
Respond
Recover
Identify critical enterprise processes and assets
Document information flows
Maintain hardware and software inventory
Establish policies for cybersecurity that include roles and responsibilities
Identify threats, vulnerabilities, and risk to assets
Manage access to assets and information
Protect sensitive data
Conduct regular backups
Protect your devices
Manage device vulnerabilities
Train users
Test and update detection processes
Maintain and monitor logs
Know the expected data flows for your enterprise
Understand the impact of cybersecurity events
Ensure response plans are tested
Ensure response plans are updated
Coordinate with internal and external stakeholders
Communicate with internal and external stakeholders
Ensure recovery plans are updated
Manage public relations and company reputation
Identifies vulnerabilities in software and systems
Guides risk assessment
Provides steps for patching and mitigation
Useful for continuous monitoring
Provides a collaborative and engaged community
| Objectives |
|---|
Key objectives of this chapter
|
Add access controls
Encrypt data in transit and at rest
Log and audit data access
Periodically review classifications
Backup and restoration procedures
Change control procedures
Proper data disposal
Highly sensitive information
Unauthorized use or disclosure could seriously and adversely impact Travelers, its business or its competitive advantage.
Warrants special protection and is identified by Travelers Policy
Sensitive information whose unauthorized use or disclosure could negatively impact Travelers, its business, or its competitive advantage
Includes identifiable personal information that does not meet the definition of Regulated Personal Information
Commonly shared within Travelers
Does not meet the standard for Restricted information, Regulated Personal Information, or Confidential information but is nevertheless not intended for distribution outside Travelers
Is or has been made freely available outside of Travelers or is intended for public use
| Objectives |
|---|
Key objectives of this chapter
|
Decompose the application
Determine and rank threats
Determine countermeasures and mitigations
Create use cases to understand how the application is used
Identifying entry points to see where a potential attacker could interact with the application
Identifying assets (items or areas that the attacker would be interested in)
Identifying trust levels that represent the access rights that the application will grant to external entities
Data flow diagrams can help illustrate
Use a threat categorization methodology
STRIDE
Application Security FRAME
PASTA
DREAD
Identify threats from the attacker
Identify the defensive perspective
Use threats to build threat trees
One tree for each threat goal
| Threat | Desired Property |
|---|---|
Spoofing |
Authenticity |
Tampering |
Integrity |
Repudiation |
Non-repudiation |
Information disclosure |
Confidentiality |
Denial of service |
Availability |
Elevation of privilege |
Authorization |
| Threat Category | Description |
|---|---|
Damage |
How bad would an attack be? |
Reproducibility |
How easy is it to reproduce the attack? |
Exploitability |
How much work is it to launch the attack? |
Affected users |
How many people will be impacted? |
Discoverability |
How easy is it to discover the threat? |
|== |Objectives
a|Key objectives of this chapter
Discuss MongoDB security best practices
Learn about MongoDB database encryption |==
MongoDB provides several authentication mechanisms
SCRAM
x.509
LDAP
Create separate users with different roles to limit access
Reduces the risk of data leaks
Recommended to whitelist specific IP addresses for remote connections
Use role-based access control to define and enforce access permissions for different users or processes accessing MongoDB
Helps ensure that only authorized users have the necessary privileges
Encrypting your data adds an extra layer of security
MongoDB provides features for data encryption, including encryption at rest and encryption in transit
Implementing encryption helps protect sensitive data from unauthorized access
Regularly update MongoDB to the latest version to ensure that you have the latest security patches and bug fixes
MongoDB releases updates and security patches to address vulnerabilities and improve security
Ensure that you properly validate and sanitize user input to prevent common security vulnerabilities such as
NoSQL injection
Cross-site scripting (XSS) attacks
Enable auditing and monitoring features provided by MongoDB to track and log activities in the database
Can help detect and investigate any suspicious or unauthorized activities
To encrypt data in MongoDB, you can use the Client-Side Field Level Encryption (CSFLE) feature.
IMPORTANT: MongoDB cannot encrypt existing data (If you have existing data, you’ll need to follow additional steps to encrypt it.)
MongoDB also provides encryption at rest, which encrypts the data files stored on disk, ensures that the data remains encrypted even if the physical storage is compromised
=HTTP Security Headers
| Objectives |
|---|
Key objectives of this chapter
|
HTTP Security Headers are a set of response headers that instruct the browser on how to behave when handling your web application.
These headers add an extra layer of security, preventing various attacks and vulnerabilities.
Some common security headers include Content Security Policy (CSP), X-XSS-Protection, X-Frame-Options, etc.
A crucial security package that helps secure your HTTP headers and protect your MERN applications from common web vulnerabilities.
Writing these headers manually can be cumbersome and error-prone.
helmet.js simplifies the process by providing an easy-to-use middleware to set these headers securely.
It is widely used, well-maintained, and compatible with Express.js, a popular framework in MERN stack development.
Before using helmet.js, we need to install it in our MERN application.
Open your terminal and run: npm install helmet
Import helmet in your Express.js server file:
const express = require('express');
const helmet = require('helmet');
const app = express();
// Use helmet middleware
app.use(helmet());A critical security header is Content Security Policy (CSP)
CSP restricts the sources from which your application can load content, mitigating XSS and data injection attacks
Implement CSP using helmet.js
const express = require('express');
const helmet = require('helmet');
const app = express();
// Use helmet middleware with Content Security Policy
app.use(helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'"],
styleSrc: ["'self'", "'unsafe-inline'"]
}
}));X-XSS-Protection header enables the browser’s Cross-Site Scripting (XSS) filter
X-Frame-Options prevents your application from being embedded in a frame on another site, mitigating clickjacking attacks
const express = require('express');
const helmet = require('helmet');
const app = express();
// Use helmet middleware with X-XSS-Protection and X-Frame-Options
app.use(helmet.xssFilter());
app.use(helmet.frameguard({ action: 'sameorigin' }));| Objectives |
|---|
Key objectives of this chapter
|
The Virtual DOM provides some security benefits
Does not address all security concerns and should be part of a broader security strategy
Consider:
Security Vulnerabilities in Dependencies
Server-Side Rendering (SSR) Vulnerabilities
Proper Use of Props and State
Keeping your packages and dependencies up to date helps reduce vulnerabilities
Make sure to regularly check for updates and apply them to your project
Ensure that sensitive data is encrypted both when stored and transmitted over the network
Helps protect the confidentiality of the data
Use encryption libraries or frameworks to implement encryption in your React application
Properly authenticate and authorize users to access your application
Use secure authentication mechanisms such as JSON Web Tokens (JWT)
Implement authorization checks to control access to different parts of your application
Validate and sanitize user input to prevent common security vulnerabilities such as cross-site scripting (XSS) and SQL injection attacks
Use libraries or frameworks that provide input validation and sanitization features
XSS attacks can be prevented by properly validating and sanitizing user input
Use security headers like Content Security Policy (CSP) to mitigate the risk of XSS attacks
If your application uses sessions, make sure to handle session management securely
Use secure session storage mechanisms and implement measures to prevent session hijacking or session fixation attacks
Use secure communication protocols such as HTTPS to encrypt the communication between the client and server
Helps protect the integrity and confidentiality of the data transmitted over the network
Familiarize yourself with React-specific security best practices
This includes disabling any instruction-containing markup, using snippet libraries, conducting code audits, and following React security checklists
Writing modular and readable code helps improve maintainability and reduces the risk of introducing security vulnerabilities
Follow best practices for code organization, naming conventions, and documentation for your team
Regularly perform security testing on your application to identify and address any security vulnerabilities
This can include manual code reviews, automated security scanning, and penetration testing
|== |Objectives
a|Key objectives of this chapter
Discuss best practices to keep Node secure
Explore resources to secure Node |==
Keep your codebase up to date by regularly updating third-party packages and dependencies
Helps to reduce vulnerabilities and ensures that you are using the latest security patches
Ensure that sensitive data is encrypted both when stored and transmitted over the network
Helps to protect the confidentiality of the data and prevent unauthorized access
Follow best practices for secure authentication in MERN stack applications
This includes using:
Strong password hashing algorithms
Implementing multi-factor authentication
Protecting against common vulnerabilities such as SQL injections and cross-site scripting (XSS) attacks
Take advantage of security linters, such as ESLint with security rules or Snyk, to identify and fix potential security issues in your code
These linters can help catch common security vulnerabilities and enforce best practices
Ensure that data transmitted over the network is done securely using HTTPS
Helps to protect the integrity and confidentiality of the data during transit
Implement proper access controls and permissions to restrict unauthorized access to sensitive resources
Use role-based access control (RBAC) or other access control mechanisms to enforce least privilege principles
Always validate and sanitize user input to prevent common security vulnerabilities such as SQL injections and cross-site scripting (XSS) attacks
Use input validation techniques and sanitize user input before using it in database queries or rendering it in HTML templates
Set up logging and monitoring mechanisms to track and detect any suspicious activities or security incidents
Monitor logs and system metrics to identify potential security breaches and respond to them in a timely manner
Conduct regular security testing, including vulnerability scanning and penetration testing, to identify and address any security weaknesses in your application
Helps to identify and fix vulnerabilities before they can be exploited by attackers
Remember that security is not limited to just Node.js
Ensure that you follow security best practices for all components of the MERN stack
Security is a continuous process
Stay informed about the latest security vulnerabilities
Seek out groups and mentors to support you